Repository navigation
Add SendBatch to send several messages over one connection - #33
Conversation
The workflow set no permissions, so the job inherited the repository's token permissions, which can include write access. Set contents: read explicitly to prevent inherited write access and address the CodeQL actions/missing-workflow-permissions warning.
any is an alias of interface{}, so existing Logger implementations and
the generated mocks stay compatible.
Previously, Send ended the SMTP session after each message, including when a client was supplied through the SMTP option, so a batch of emails meant one session per message. SendBatch reuses one connection, authenticating once when credentials are configured and sending each valid message in its own transaction. After a rejection by the server it continues only if RSET succeeds. RSET comes from the new single-method SMTPResetter interface, which smtp.Client implements; SMTPClient is unchanged, so existing implementations keep compiling. A failed or unavailable reset, a connection failure or a cancelled or expired context stops the rest of the batch. BatchError reports the result of every message, and its Is and As methods let errors.Is and errors.As look into it on Go 1.19, which does not follow a multi-error Unwrap. The authentication, transaction and QUIT steps of SendContext move into helpers shared with SendBatch, without a change in its behaviour.
umputun
left a comment
There was a problem hiding this comment.
a few small things before merge:
email.go:262-282- if ctx is cancelled while a message is in flight on a connectionSendBatchopened itself, the ctx watcher closes the connection. That message then fails with "bad from address ...: use of closed network connection", the rest get the same error, anderrors.Is(err, context.Canceled)is false. The same cancel between two messages givescontext.Canceled. Fix: after a failure, checkctx.Err()beforeresetand wrap it for this message and the rest (below). Also add a test with a server that stalls mid-message; the current cancel test uses an injected client, so it covers only a cancel between messages:
if cerr := ctx.Err(); cerr != nil {
errs[i] = fmt.Errorf("%w: %v", cerr, err)
fillUnsent(errs[i+1:], cerr)
break
}email.go:88,email.go:220,README.md:75,README.md:86- failed entries are called "not sent". When the connection drops after the server got the message body, the message may already be delivered, so a caller who retries the "not sent" entries delivers it twice. Fix: say "failed" in these places. The entries after a broken session were never attempted, so their "not sent" text is right.README.md:74-75- "a message the server rejects doesn't stop the batch" holds only for a client withReset(). A customSMTPclient without it stops at the first rejection. Fix: add a clause about it. The godoc atemail.go:77is off the other way: "stops at the first failure" should be "stops at the first message the server rejects", because a message rejected before sending doesn't stop it.README.md:82-89- the example handles only*BatchError. If someone copies it as is, a dial or auth error, where nothing was sent, is silently dropped. Fix: return any other error before the loop.email.go:76-SMTPResetteris only used in the type assertion, and a custom client needs nothing more than aReset() errormethod. Pls make it unexported and name that method in theSendBatchgodoc. That keeps the public API smaller.email.go:325-fillUnsentis called only fromSendBatch, pls make it a method onSender.batch_test.go:100-111- pls generate theResetmock with moq, like the other mocks, in place of the hand-written method. With an unexported interface,moq -out mocks/resetter.go -pkg mocks -skip-ensure -fmt goimports . resetter:ResetterMockstill gives an exported mock. Add the//go:generateline next to the existing ones, and embed both mocks in the test client.- the comments in
batch_test.go(lines 24, 40, 84, 100, 141, 235) and onsendMessage,authenticateandtransactionmostly repeat what the code says, pls drop them.
Previously, cancelling the context while a message was in flight on a connection SendBatch had opened closed that connection, and the message and the rest of the batch failed with a closed network connection error that did not match context.Canceled. A deadline could do the same through the connection deadline, which is set to the context's and can fire before ctx.Err reports it. Now a transaction failure after the context is done or its deadline has passed is reported with the context error, keeping the SMTP error text, and the rest of the batch gets the context error, as with a cancellation between messages.
SendBatch only type-asserts the client to it, and a custom client needs nothing more than a Reset() error method, so the interface does not belong in the public API; the SendBatch documentation names the method and says the batch stops at the first message the server rejects without it. The test client embeds the moq-generated ResetterMock next to SMTPClientMock in place of a hand-written Reset method, fillUnsent becomes a method of Sender, and comments that repeat the code are gone.
A message whose connection drops after the server got its body may already be delivered, so calling it not sent invites a retry that delivers it twice. Messages after a broken session are never attempted and keep "not sent". The README documents that a custom client without a Reset() error method stops the batch at the first message the server rejects, and its example returns errors other than BatchError, where nothing was sent, before looking at the failed messages.
A message the server rejected just as the context was cancelled or its deadline passed was reported with the context error, preserving the reply only as text and hiding its *textproto.Error from errors.As. The context error is now applied to that message only when the failure is not a server reply; the rest of the batch still gets the context error.
|
Thanks a lot for the review. All eight points are addressed in the last four commits. After a failed transaction, The rest is as you asked:
|
umputun
left a comment
There was a problem hiding this comment.
last round's items check out, two small things left:
email.go:287- the in-flight fix doesn't cover RSET. If ctx is cancelled or its deadline passes while RSET after a rejection is still waiting for the server, the watcher closes the connection andReset()fails with "use of closed network connection" (or an i/o timeout for a deadline). The rest of the batch get that error, soerrors.Is(err, context.Canceled)is false again (context.DeadlineExceededfor a deadline), same as last round's first point. Fix: checkctxDonewhen reset fails and keeperrs[i]as the server reply. Pls add a test for it too: 550 on RCPT, then ctx ends during RSET, either with a stalled server or with aResetFuncthat cancels ctx and returns a plain error likeerrors.New("connection closed")(notcontext.Canceled, it would pass without the fix):
if rerr := em.reset(client, err); rerr != nil {
if cerr := ctxDone(ctx); cerr != nil {
rerr = fmt.Errorf("%w: %v", cerr, rerr)
}
em.fillUnsent(errs[i+1:], fmt.Errorf("not sent, the session ended after message %d failed: %w", i, rerr))
break
}batch_test.go:316- pls drop "the message is received and never answered", it's the same kind of comment as the ones removed last round.
When the context ended during RSET after a server rejection, the remaining messages got a connection error that hid the context error. A failed reset now wraps the context error when the context is done, keeping the reset error as text. The rejected message keeps the server reply.
|
Thanks a lot, both are addressed in the last two commits:
|
Previously,
Sendended the SMTP session after each message, including when a client was supplied through theSMTPoption. After this change,SendBatchreuses one connection, authenticating once when credentials are configured and sending each valid message in its own transaction. The connection is used for one call, with no persistent pool.After a rejection by the server,
SendBatchcontinues only if RSET succeeds. RSET is used when the client has aReset() errormethod, assmtp.Clientdoes;SMTPClientis unchanged, so existing implementations and mocks keep compiling. A custom client without that method stops the batch at the first message the server rejects. A failed reset, a connection failure or a cancelled or expired context stops the rest of the batch. A done context closes a connectionSendBatchopened, failing the message in flight, while a client from theSMTPoption finishes its current message; a message that fails this way is reported with the context error, and may have been delivered all the same.BatchErrorreports the result of every message, anderrors.Isanderrors.Aslook into it on every supported Go version. Any other error means the session could not be set up and nothing was sent.SendContextbehaves as before; its authentication, transaction and QUIT steps moved into helpers it shares withSendBatch.The PR also sets the token permissions of the CI workflow, the only workflow in the repository, to
contents: read. The workflow set none, so the token had the repository default, which on master meant write access to contents, issues, pull requests, packages, pages, statuses, checks and security events, among others. The job checks out, builds, tests, lints and sends coverage to Coveralls, and writes nothing to GitHub, so the token now reads the repository contents and metadata only; every CI step passes with it, the Coveralls upload included. This resolves the CodeQL missing-workflow-permissions alert once merged. The PR also replacesinterface{}with its aliasany.The tests run a batch against a fake SMTP server that refuses a nested MAIL, so the test fails without RSET, and against one that receives a message and never answers it, where the test cancels the context. The reset, broken connection, cancellation and session setup paths are also covered with the mock client. The suite passes with Go 1.19, the version in go.mod that CI uses, and with Go 1.27.
Resolves #7.